package com.alibaba.citrus.ots.application.report.ability.facade.service;

import com.alibaba.citrus.ots.common.lock.RedisLock;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.otsapplicationadaptersdk.mncurrentaccount.service.MnCurrentAccountService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.CurrentAccountData;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SIORZTCUSTOMERWLZYBBAsynOUTRequest;
import com.epoch.app.otsapplicationadaptersdk.service.SapService;
import com.epoch.app.otsapplicationreportsdk.cometomonthreport.dto.*;
import com.epoch.app.otsapplicationreportsdk.cometomonthreport.service.ComeToMonthReportService;
import com.epoch.app.otsapplicationreportsdk.contants.OtsApplicationReportSdkConstants;
import com.epoch.app.otsapplicationreportsdk.model.dto.MonthReportConfigLoadListRequest;
import com.epoch.app.otsapplicationreportsdk.monthreportconfig.model.MonthReportConfig;
import com.epoch.app.otsapplicationreportsdk.monthreportconfig.service.MonthReportConfigService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author hhj
 * @description: 平台请求sap往来账创建 ,刷新数据->SAP接口
 * @date 2023/10/7 21:24
 */
@Component
@Primary
public class ComeToMonthReportServiceImpl implements ComeToMonthReportService {
    private final Log log = Log.getLogger(ComeToMonthReportServiceImpl.class);

    @Resource
    private UnifiedInventoryService unifiedInventoryService;

    // 保存 往来账Service
    @Resource
    private ComeToMonthReportService comeToMonthReportService;
    @Resource
    private MnCurrentAccountService currentAccountService;
    @Resource
    private SapService sapService;
    @Resource
    private MonthReportConfigService monthReportConfigService;


    @Override
    public Result<String> refreshData(RefreshDataRequest refreshDataRequest) {
        if (StringUtils.isBlank(refreshDataRequest.getKunnr()) || StringUtils.isBlank(refreshDataRequest.getYearMonth()) || !isYearMonth(refreshDataRequest.getYearMonth())) {
            log.error("{},刷新参数有问题！", JSON.toJSONString(refreshDataRequest));
            return Result.fail("300", "参数为空或日期格式有误！");
        }

        RefreshDateHandleRequest refreshDateHandleRequest = new RefreshDateHandleRequest();
        refreshDateHandleRequest.setId(refreshDataRequest.getKunnr());
        RefreshDateHandleResponse refreshDateHandleResponse;
        try {
            // 通过销售组织id 查询销售组织code
            refreshDateHandleResponse = comeToMonthReportService.refreshDateHandle(refreshDateHandleRequest);
            log.info("通过销售组织id:{}, 查询销售组织code :{}", refreshDateHandleRequest.getId(), refreshDateHandleResponse.getKunnr());

        } catch (Exception e) {
            throw new RuntimeException("调用comeToMonthReportService.refreshDateHandle 失败，入参：" + JSON.toJSONString(refreshDateHandleRequest));
        }

        // 范围内售达方集合
        List<String> list = queryKunnr();
        if (list.contains(refreshDateHandleResponse.getKunnr())) {
            RefreshRequest refreshRequest = new RefreshRequest();
            refreshRequest.setYearMonth(refreshDataRequest.getYearMonth());
            refreshRequest.setKunnr(refreshDateHandleResponse.getKunnr());
            // 执行刷新
            this.refresh(refreshRequest);
        }
        return Result.success("刷新成功！");
    }

    final String REFRESH_LOCK = "REFRESH_LOCK_";

    public Object refresh(RefreshRequest refreshRequest) {

        // 检测是否在刷新范围内
        try (RedisLock lock = new RedisLock(BcOtsConstants.REDIS_CACHE_CODE(), REFRESH_LOCK + SapAndCrmFieldDealUtils.generateIdField(refreshRequest.getKunnr() + "" + refreshRequest.getYearMonth()),
                5 * 60 * 1000, 10 * 60 * 1000)) {
            if (!lock.lock()) {
                log.info("数据刷新中，请勿多次点击:{}", refreshRequest);
                return null;
            }
            return requestRefresh(refreshRequest.getYearMonth(), refreshRequest.getKunnr());
        } catch (Throwable e) {
            return Result.fail("500", e.getMessage());
        }
    }

    /**
     * 通过年月及售达方编码 请求数据回调
     */
    public Object requestRefresh(String yearMonth, String kunnr) {
        SIORZTCUSTOMERWLZYBBAsynOUTRequest siorztcustomerwlzybbAsynOUTRequest = new SIORZTCUSTOMERWLZYBBAsynOUTRequest();
        siorztcustomerwlzybbAsynOUTRequest.setIMonth(yearMonth);
        siorztcustomerwlzybbAsynOUTRequest.setLow(kunnr);
        sapService.sIORZTCUSTOMERWLZYBBAsynOUT(siorztcustomerwlzybbAsynOUTRequest);
        return null;
    }

    public Result<Void> mnCurrentAccountSchedule() {
        // 获取配置后所有的售达方列表
        List<String> list = queryKunnr();
        RefreshRequest refreshRequest = new RefreshRequest();
        refreshRequest.setYearMonth(currentDateYM());
        if (list.size() > 0) {
            // 执行刷新
            list.forEach(kunnr -> {
                refreshRequest.setKunnr(kunnr);
                refresh(refreshRequest);
            });
        }
        return null;
    }

    @NotNull
    private List<String> queryKunnr() {
        // 获取公司配置
        String currentAccounts = OtsApplicationReportSdkConstants.CURRENT_ACCOUNT_JOB_PULL_ORG();
        String[] split = currentAccounts.split(",|，");

        List<String> list = Lists.newArrayList();

        // 传入空值 查询全部拥有客服负责人的 销售组
        if (split.length > 0) {
            // 查询所有销售组织
            QuerySaleScopeListByRelationIdRequest querySaleScopeListByRelationIdRequest = new QuerySaleScopeListByRelationIdRequest();
            querySaleScopeListByRelationIdRequest.setRelatedOrganizationType(Integer.valueOf(OtsApplicationReportSdkConstants.SALES_ORGANIZATION()));
            Arrays.stream(split).forEach(e -> {
                querySaleScopeListByRelationIdRequest.setRelatedOrganizationId(e);
                // 通过销售组织 查询 售达方列表
                list.addAll(comeToMonthReportService.querySaleScopeListByRelationId(querySaleScopeListByRelationIdRequest).getResult());
            });
        }

        return list;
    }

    private String currentDateYM() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        String format = simpleDateFormat.format(new Date());
        return format;
    }

    private Boolean isYearMonth(String yearMonth) {
        Pattern pattern = Pattern.compile("[0-9]{4}+(0[1-9]{1}|12|11|10)");
        Matcher isDou = pattern.matcher(yearMonth);
        return isDou.matches();
    }

}
